var ns, WXPhotoPicker, bmLocation, actionnewdialog;
app = new Vue({
    el: '#app',
    data: {
        newform: {
            PlanID:0,
            ProjectID: 0,
            ProjectName: '',
            CategoryID: 0,
            CategoryName:'',
            ServiceContent: '',
            ServiceEndTime: '',
            InChargeUserID: '',
            UserName:'',//整改处理人
            CheckUserID:0,//验收人id
            CheckUserName:'',//验收人姓名
            ComeFrom:1,//1-临时任务，2-考核任务，3-检查任务
            RelatedID:1,//2-考核任务，3-检查任务
            ResDepartmentID:0,
            ResDepartmentName:"",
            DeductNumber:0,
            action:'savequalitycontrol'
        },
        ID:0,
        imglist: [],
        imgEditlist: [],  
        ProjectList:[],
        CategoryList: [],
        maxuploadcount: CONFIG.maxuploadcount,
        IsRoomOpen:false,//是否打开问题分类
    },
    methods: {
        get_data: function() {
            var that = this;
            var options = {
                action: 'getqualitycontrolparams'
            };
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    that.ProjectList = data.list;
                    if (data.list.length > 0) {
                        that.newform.ProjectID = data.list[0].ID;
                        that.newform.ProjectName = data.list[0].Name;
                    }
                    that.getactions(that.newform.ProjectID);
                    //加载下拉列表数据
                    that.initPicker();
                    if(that.ID>0){
                        that.get_editdata();
                    }
                    
                }
            });
        }, 
        //选择责任部门
        doOpenResDepartment(){
            var that = this;
            ns.openWin('chooseorganization', '选择责任部门', {
            });
        },
        do_select_time: function() {
            var that = this;
            api.openPicker({
                type: 'date',
                date: that.newform.ServiceEndTime,
                title: '选择日期'
            }, function(ret, err) {
                if (ret) {
                    var year = ret.year;
                    var month = (ret.month >= 10 ? ret.month : '0' + ret.month);
                    that.newform.ServiceEndTime = year + '/' + month + '/' + day;
                }
            });
        },
        do_save: function() {
            var that = this;
            if (that.newform.ProjectID <= 0) {
                api.toast({
                    msg: '请选择项目',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.CategoryID <= 0) {
                api.toast({
                    msg: '请选择问题分类',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.InChargeUserID == '') {
                api.toast({
                    msg: '请选择处理人',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.CheckUserID == ''||that.newform.CheckUserID<=0) {
                api.toast({
                    msg: '请选择验收人',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.ServiceContent == '') {
                api.toast({
                    msg: '请填写问题描述',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            } 
            if (that.newform.ServiceEndTime == '') {
               api.toast({
                   msg: '请填写整改期限',
                   duration: 2000,
                   location: 'bottom'
               });
               return;
            }
            var date = new Date(that.newform.ServiceEndTime.replace(/-/g, "/"));
            if ((new Date()).valueOf() >= date.valueOf()) {
               api.toast({
                   msg: '整改期限不能早于当前时间',
                   duration: 2000,
                   location: 'bottom'
               });
               return;
            }
            if(that.ID>0){
                that.saveEdit();
            }else{
                that.do_save_process();
            }
           
        },
        saveEdit:function(){
            var that = this;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            var options={};
            options.ID=that.ID;
            options.ProjectID=that.newform.ProjectID;
            options.ProjectName=that.newform.ProjectName;
            options.CategoryID=that.newform.CategoryID;
            options.CategoryName=that.newform.CategoryName;
            options.InChargeUserID=that.newform.InChargeUserID;
            options.UserName=that.newform.UserName;
            options.CheckUserID=that.newform.CheckUserID;
            options.CheckUserName=that.newform.CheckUserName;
            options.ServiceContent=that.newform.ServiceContent;
            options.ServiceEndTime=that.newform.ServiceEndTime;
            options.ResDepartmentID=that.newform.ResDepartmentID;
            options.DeductNumber=that.newform.DeductNumber;
            options.action="editqualitycontrol";
            ns.post(options, function(succeed, data, err) {
                if(succeed){
                    if(data.status){
                        api.toast({
                            msg: '修改成功',
                            duration: 2000,
                            location: 'bottom'
                        });
                        api.sendEvent({
                                name: 'updata_task_con',
                            });
                            api.sendEvent({
                                name: 'reloadservicelist',
                            });
                            setTimeout(function () {
                                api.closeWin();
                            }, 500);

                    }else{
                        api.toast({
                            msg: '修改失败',
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                    
                }else{
                    api.toast({
                        msg: '修改失败',
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist,
                }
            })
        },
        do_save_process: function() {
            var that = this;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            ns.post(that.newform, function(succeed, data, err) {
                if (succeed) {
                    if(data.status){
                        // api.alert({
                        //     title: '',
                        //     msg: '整改任务已发送至整改处理人，您可以在右上角-【历史工单】中查看任务进度',
                        // }, function(ret, err) {});
                        api.toast({
                            msg: '操作成功',
                            duration: 2000,
                            location: 'bottom'
                        });
                        api.sendEvent({
                            name: 'reloadservicelist',
                        });
                        api.sendEvent({
                            name: 'loadservicelist',
                        });
                        api.sendEvent({
                            name: 'saveservicelist',
                        });
                        api.sendEvent({
                            name: 'home_new_updata',
                            extra: {
                                key1: 'value1',
                            }
                        });  
                        setTimeout(function() {
                            api.closeWin();
                        }, 300)
                        return;
                    }
                    else if(data.Msg){
                        api.toast({
                            msg: data.Msg,
                            duration: 2000,
                            location: 'bottom'
                        });
                        return;
                    }
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        //选择项目
        do_select_project:function(){
            var that=this;

        },
        do_choose_user: function (type) {
            var that = this;
            var title='';
            if(type==1){
                title="选择处理人"
            }
            if(type==2){
                title="选择验收人"
            }
            ns.openWin('quality_chooseperson', title, {
                ProjectID: that.newform.ProjectID,
                type:type
            });
        },
        //上传图片
        choose_picture: function() {
            var that = this;
            ns.confirmPer('camera', function() {
                that.choose_picture_start();
            })
        },
        choose_picture_start:function(){
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function(ret, err) {
                //拍照
                if(ret.buttonIndex==1){ 
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if(ret.buttonIndex==2){
                    that.choose_picture_album();
                    return;
                } 
                //取消 
                else{
                    return false;  
                }  
            });
        },
        upload_choose_picture:function(){
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: true,
            }, function(ret, err) {
                if (ret&&ret.data) {
                    that.imglist.push({
                        ID: 0,
                        url: ret.data,
                        thumbPath: ret.data,
                        isupload: true
                    });
                } 
            });
        },
        choose_picture_album:function(){
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.imglist.length,
                type:'image',
            }, function(ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            that.imglist.push({
                                ID: 0,
                                url: item.path,
                                thumbPath: item.path,
                                isupload: true
                            });
                        });
                    }
                }
            });
        },
        remove_img: function (index, type, id) {
            var that = this;
            if (type == 1) {
                that.imglist.splice(index, 1);
            } else {
                for (var i = 0; i < that.imgEditlist.length; i++) {
                    var item = that.imgEditlist[i];
                    if (item.ID == id) {
                        that.imgEditlist.splice(i, 1);
                    }
                }
                that.do_remove_uploadimg(id);
            }
        },
        do_remove_uploadimg: function(id) {
            var that = this;
            var options = {
                action: 'doremoveproductimg',
                RelatedID: id,
                Type:1
            }
            ns.post(options, function(succeed, data, err) {
            });
        },
        do_viewimages: function(activeIndex,type) {
            var that = this;
            var imageUrls = [];
            if(type==1){
                for (var i = 0; i < that.imglist.length; i++) {
                    imageUrls.push(that.imglist[i].url);
                }
            }
            if(type==2){
                for (var i = 0; i < that.imgEditlist.length; i++) {
                    imageUrls.push(that.imgEditlist[i].imgurl);
                }
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        doChooseUser: function (item) {
            var that = this;
            if (item.length>0) {
                that.newform.InChargeUserID = item[0].id;
                that.newform.UserName = item[0].text;
            }        
        },
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                         // 选择项目
                        var pickerProject = new $.PopPicker({
                            layer: 1,
                            fileID: 'ID',
                            fileName:'Name',
                        });
                        var projectData = _this.ProjectList || [];
                        pickerProject.setData(projectData);
                        var showProjectPickerButton = doc.getElementById('chooseproject');
                        showProjectPickerButton.addEventListener('click', function (event) {
                            pickerProject.show(function (items) {
                                _this.newform.ProjectID = items[0].value;
                                _this.newform.ProjectName = items[0].text;
                                _this.getactions(_this.newform.ProjectID);
                                
                                //返回 false 可以阻止选择框的关闭
                                //return false;
                            });
                        }, false);
                });
            })(mui, document);
        },
        //打开问题分类
        do_openQuestion:function(id){
            var that = this;
            that.IsRoomOpen=true;
            that.chooseID = id;

        },
        doCloseRoom:function(){
            var that = this;
            that.IsRoomOpen=false;
        },
        
        //选择分类
        doSelectRoom:function(item){
            var that = this;
            var nowDate=new Date();
            that.IsRoomOpen=false;
            that.newform.CategoryID = item.ID;
            that.newform.CategoryName = item.CategoryName;
            that.newform.CheckUserID = item.CheckUserID;
            that.newform.CheckUserName = item.CheckUserName;
            var date='';
            if(item.LimitTime>0){
                date= new Date(nowDate.setDate(nowDate.getDate()+item.LimitTime));
                
            }else{
                date = nowDate;
            }
            that.newform.ServiceEndTime = moment(date).format('YYYY/MM/DD HH:mm');
            // that.newform.ServiceEndTime=date.getFullYear()+"-"
            //     +((date.getMonth()+1)>9?date.getMonth()+1:"0"+(date.getMonth()+1))+"-"
            //     +(date.getDate()>9?date.getDate():"0"+date.getDate());
        },
        getactions:function(id){
            var nowDate=new Date();
            var that=this;
            var list=[];
            that.CategoryList=[];
            var options = {
                ProjectID:id,
                action: 'getqualitycontrolcategory'
            };
            ns.get(options, function (succeed, data, err) {
                if (succeed) {
                    that.CategoryList = data.list;
                    if (data.list.length > 0) {
                        that.newform.CategoryID = data.list[0].ID;
                        that.newform.CategoryName = data.list[0].CategoryName;
                        that.newform.CheckUserID = data.list[0].CheckUserID;
                        that.newform.CheckUserName = data.list[0].CheckUserName;
                        var date='';
                        if(data.list[0].LimitTime>0){
                           date= new Date(nowDate.setDate(nowDate.getDate()+data.list[0].LimitTime));
                           
                        }else{
                            date = nowDate;
                        }
                        that.newform.ServiceEndTime = moment(date).format('YYYY/MM/DD HH:mm');
                        // that.newform.ServiceEndTime=date.getFullYear()+"-"
                        //    +((date.getMonth()+1)>9?date.getMonth()+1:"0"+(date.getMonth()+1))+"-"
                        //    +(date.getDate()>9?date.getDate():"0"+date.getDate());
                    }

                }
            });
        },
        //编辑
        get_editdata:function(){
            var that = this;
            var options = {};
            options.ID = that.ID;
            options.action = "getqualitycontroldetail";
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.newform.ProjectID=data.form.ProjectID;
                    that.newform.ProjectName=data.form.fullname;
                    that.newform.CategoryID=data.form.CategoryID;
                    that.newform.CategoryName=data.form.CategoryName;
                    that.newform.InChargeUserID=data.form.InChargeUserIDList[0];
                    that.newform.UserName=data.form.InChargeUserNames;
                    that.newform.CheckUserID=data.form.CheckUserID;
                    that.newform.CheckUserName=data.form.CheckUserName;
                    that.newform.ServiceContent=data.form.ServiceContent;
                    that.newform.ResDepartmentID=data.form.DepartmentNameId;
                    that.newform.ResDepartmentName=data.form.DepartmentName;
                    that.newform.DeductNumber=(data.form.DeductNumber!=undefined&&data.form.DeductNumber>=0)?data.form.DeductNumber:0;
                    that.getDate(data.form.ServiceEndTime);
                    that.imgEditlist=data.form.imagelist;
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });

        },
        getDate: function (dt) {
            var that=this;
            var myDate = new Date(dt);
            that.newform.ServiceEndTime = moment(myDate).format('YYYY/MM/DD HH:mm');
        },
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    var btn = document.querySelector('#choosedatetime');
                    btn.addEventListener('tap', function () {
                        var _self = this;
                        if (_self.picker) {
                            if(_this.newform.ServiceEndTime){
                                _self.picker.setSelectedValue(_this.newform.ServiceEndTime);//回显
                            }
                            _self.picker.show(function (rs) {
                                _this.newform.ServiceEndTime = rs.value;
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        } else {
                            var optionsJson = this.getAttribute('data-options') || '{}';
                            var options = JSON.parse(optionsJson);
                            var id = this.getAttribute('id');
                            _self.picker = new $.DtPicker(options);
                            if(_this.newform.ServiceEndTime){
                                _self.picker.setSelectedValue(_this.newform.ServiceEndTime);//回显
                            }
                            _self.picker.show(function (rs) {
                                var timer = setTimeout(function () {
                                    clearTimeout(timer);
                                    _this.newform.ServiceEndTime = rs.value;
                                }, 300);
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        }
                    }, false);

                });
            })(mui, document);
        },
    }
});
apiready = function() {
    api.parseTapmode();
    ns = window.Foresight.Util;
    WXPhotoPicker = api.require('WXPhotoPicker');
    app.newform.RelatedID = api.pageParam.RelatedID ||0;
    app.newform.ComeFrom = api.pageParam.ComeFrom ||1;
    app.newform.PlanID = api.pageParam.PlanID ||0;
    app.ID = api.pageParam.ID ||0;
    app.initPicker();
    app.get_data();
    api.addEventListener({
        name: 'do_qualitychoose'
    }, function (ret, err) {
        if (ret) {
            if(ret.value.type==1){
                app.newform.UserName=ret.value.item.FinalRealName;
                app.newform.InChargeUserID=ret.value.item.FinalUserID;
            }
            if(ret.value.type==2){
                app.newform.CheckUserName=ret.value.item.FinalRealName;
                app.newform.CheckUserID=ret.value.item.FinalUserID;
            }
            
        }
    });

    //选择责任部门返回
    api.addEventListener({
        name: 'dosavequalitycontrol'
    }, function (ret) {
        app.newform.ResDepartmentName = ret.value.item.text;
        app.newform.ResDepartmentID = ret.value.item.id;

    })

};
